from sqlalchemy.orm import Session
from schema import Soil_schema
from model import Soil_model



def get_Soil(db: Session, ID: int):
    return db.query(Soil_model.Soil).filter(Soil_model.Soil.ID == ID).first()


def get_all_Soil(db: Session):
    return db.query(Soil_model.Soil).all()


def delete_Soil(db: Session, ID):
    to_delete = db.query(Soil_model.Soil).filter(Soil_model.Soil.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Soil(db: Session, Soil: Soil_schema.Soil):
    db_Soil = Soil_model.Soil(
        RetrievalTime=Soil.RetrievalTime,
        FarmID=Soil.FarmID,
        AvgMoisture=Soil.AvgMoisture,
        NitrogenContent=Soil.NitrogenContent,
        PhosphorusContent=Soil.PhosphorusContent,
        PotassiumContent=Soil.PotassiumContent,
        OtherIndicators=Soil.OtherIndicators,
    )
    db.add(db_Soil)
    db.commit()
    db.refresh(db_Soil)
    return db_Soil


def update_Soil(db: Session, ID, field_name, new_value):
    db_Soil = db.query(Soil_model.Soil).filter(Soil_model.Soil.ID == ID).first()
    setattr(db_Soil, field_name, new_value)
    db.commit()
    db.refresh(db_Soil)
    return db_Soil
